package com.vietnam.power.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

public abstract class GenericDaoImpl {

	@Autowired
	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	
	public Session getActiveSession() {
		return sessionFactory.getCurrentSession();
	}

	public <T> T save(T entity) {
		sessionFactory.getCurrentSession().save(entity);
		return entity;
	}

	public <T> T saveOrUpdate(T entity) {
		sessionFactory.getCurrentSession().saveOrUpdate(entity);
		return entity;
	}

	@SuppressWarnings("unchecked")
	public <T> T merge(T entity) {
		return (T) sessionFactory.getCurrentSession().merge(entity);
	}

	public <T> void persist(T entity) {
		sessionFactory.getCurrentSession().persist(entity);
	}

	public <T> void delete(T entity) {
		sessionFactory.getCurrentSession().delete(entity);
	}

	@SuppressWarnings("unchecked")
	public <T, K extends Serializable> T findById(final Class<T> type, final K id) {
		return (T) sessionFactory.getCurrentSession().get(type, id);
	}

	@SuppressWarnings("unchecked")
	public <T> List<T> findAll(final Class<T> type) {
		return sessionFactory.getCurrentSession().createCriteria(type).list();
	}

}
